#!/usr/bin/env python3
"""
AutoGUI 项目打包脚本
使用 PyInstaller 将项目打包成可执行文件
"""

import os
import sys
import shutil
import subprocess
from pathlib import Path

def check_pyinstaller():
    """检查PyInstaller是否已安装"""
    try:
        import PyInstaller
        print(f"PyInstaller 版本: {PyInstaller.__version__}")
        return True
    except ImportError:
        print("PyInstaller 未安装，正在安装...")
        try:
            subprocess.check_call([sys.executable, "-m", "pip", "install", "pyinstaller"])
            print("PyInstaller 安装成功")
            return True
        except subprocess.CalledProcessError:
            print("PyInstaller 安装失败")
            return False

def create_spec_file():
    """创建PyInstaller规格文件"""
    spec_content = '''# -*- mode: python ; coding: utf-8 -*-

block_cipher = None

# 数据文件
datas = [
    ('config', 'config'),
    ('fonts', 'fonts'),
    ('SIMION', 'SIMION'),
    ('store', 'store'),
    ('utils', 'utils'),
    ('windows', 'windows'),
    ('scripts', 'scripts'),
]

# 隐藏导入
hiddenimports = [
    'tkinter',
    'tkinter.ttk',
    'tkinter.filedialog',
    'tkinter.messagebox',
    'numpy',
    'openpyxl',
    'psutil',
    'pyautogui',
    'cv2',
    'PIL',
    'PIL.Image',
    'PIL.ImageTk',
    'json',
    'threading',
    'subprocess',
    'queue',
    'time',
    'os',
    'sys',
    're',
    'shutil',
    'platform',
    'concurrent.futures',
    'signal',
    'logging',
    'logging.handlers',
]

a = Analysis(
    ['main.py'],
    pathex=[],
    binaries=[],
    datas=datas,
    hiddenimports=hiddenimports,
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)

pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.zipfiles,
    a.datas,
    [],
    name='AutoGUI',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=False,  # 不显示控制台窗口
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
    icon='icon.ico' if os.path.exists('icon.ico') else None,
)
'''
    
    with open('AutoGUI.spec', 'w', encoding='utf-8') as f:
        f.write(spec_content)
    
    print("已创建 AutoGUI.spec 文件")

def clean_build_dirs():
    """清理构建目录"""
    dirs_to_clean = ['build', 'dist', '__pycache__']
    for dir_name in dirs_to_clean:
        if os.path.exists(dir_name):
            shutil.rmtree(dir_name)
            print(f"已清理目录: {dir_name}")

def build_executable():
    """构建可执行文件"""
    print("开始构建可执行文件...")
    
    try:
        # 使用spec文件构建
        cmd = [sys.executable, "-m", "PyInstaller", "--clean", "AutoGUI.spec"]
        subprocess.check_call(cmd)
        print("构建成功！")
        
        # 检查输出文件
        exe_path = os.path.join("dist", "AutoGUI.exe")
        if os.path.exists(exe_path):
            file_size = os.path.getsize(exe_path) / (1024 * 1024)  # MB
            print(f"可执行文件已生成: {exe_path}")
            print(f"文件大小: {file_size:.1f} MB")
        else:
            print("错误: 可执行文件未生成")
            
    except subprocess.CalledProcessError as e:
        print(f"构建失败: {e}")
        return False
    
    return True

def create_installer_script():
    """创建安装脚本"""
    installer_content = '''@echo off
echo AutoGUI 安装脚本
echo.

REM 创建安装目录
set INSTALL_DIR=%USERPROFILE%\\Desktop\\AutoGUI
if not exist "%INSTALL_DIR%" mkdir "%INSTALL_DIR%"

REM 复制可执行文件
copy "dist\\AutoGUI.exe" "%INSTALL_DIR%\\"

REM 创建启动快捷方式
echo 正在创建桌面快捷方式...
powershell -Command "$WshShell = New-Object -comObject WScript.Shell; $Shortcut = $WshShell.CreateShortcut('%USERPROFILE%\\Desktop\\AutoGUI.lnk'); $Shortcut.TargetPath = '%INSTALL_DIR%\\AutoGUI.exe'; $Shortcut.Save()"

echo.
echo 安装完成！
echo 可执行文件位置: %INSTALL_DIR%\\AutoGUI.exe
echo 桌面快捷方式: %USERPROFILE%\\Desktop\\AutoGUI.lnk
echo.
pause
'''
    
    with open('install.bat', 'w', encoding='gbk') as f:
        f.write(installer_content)
    
    print("已创建安装脚本: install.bat")

def main():
    """主函数"""
    print("=== AutoGUI 项目打包工具 ===\n")
    
    # 检查PyInstaller
    if not check_pyinstaller():
        return
    
    # 清理构建目录
    clean_build_dirs()
    
    # 创建spec文件
    create_spec_file()
    
    # 构建可执行文件
    if build_executable():
        # 创建安装脚本
        create_installer_script()
        
        print("\n=== 打包完成 ===")
        print("可执行文件位置: dist/AutoGUI.exe")
        print("安装脚本: install.bat")
        print("\n使用说明:")
        print("1. 运行 install.bat 进行安装")
        print("2. 或直接运行 dist/AutoGUI.exe")
        print("3. 确保目标机器已安装必要的运行时库")
    else:
        print("\n=== 打包失败 ===")
        print("请检查错误信息并重试")

if __name__ == "__main__":
    main()
